import 'dart:io';
import 'package:flutter/material.dart';
import 'package:zpub_svr/com/zerogis/zpubsvr/constant/HttpParamKeyValue.dart';
import 'package:zpub_bas/com/zerogis/zpubbase/constant/BasStringValueConstant.dart';
import 'package:zpub_bas/zpub_bas.dart';
import 'package:zpub_http/zpub_http.dart';
import 'package:zpub_svr/zpub_svr.dart';
import 'package:zpub_ui/zpub_ui.dart';
import 'package:zpub_http/com/zerogis/zpubhttp/constant/MessageConstant.dart';
import 'package:zpub_dbmanager/zpub_dbmanager.dart';
import 'package:zpub_plugin/com/zerogis/zpubPlugin/widget/WidgetStatefulBase.dart';

/*
 * 网络组件：附件组件,支持本地，网络图片显示，支持查看，编辑,新增 <br/>
 * @param {Object 必传} isEdit   是否为编辑【true=编辑状态】
 * @param {Object 必传} nullable 是否为可空[1=不可空，必须要上传附件]
 * @param {Object 必传} initPara  初始化参数{major:1,minor:1,id:1}
 * 需要传入的键：<br/>
 * 传入的值类型： <br/>
 * 传入的值含义：<br/>
 * 是否必传 ：
 */
class CtrlDocWidgetBas extends WidgetStatefulBase
{
  /*
   * nullable = 是否为可空[1=不可空，必须要上传附件]
   * isEdit = 是否为编辑【true=编辑状态】
   * 初始化参数{major:1,minor:1,id:1,nullable:1,isEdit:true}
   */
  Map<String, dynamic> initPara;

  CtrlDocWidgetBas({Key key, plugin, @required this.initPara}) : super(key: key, plugin: plugin);

  State<StatefulWidget> createState()
  {
    return new CtrlDocWidgetBasState();
  }

  static String toStrings()
  {
    return "CtrlDocWidgetBas";
  }
}

/*
 * 组件功能 <br/>
 */
class CtrlDocWidgetBasState<T extends CtrlDocWidgetBas> extends WidgetBaseState<T>
{
  /*
   * 查询出来的图片集合URL地址
   */
  List<String> mediaList = [];

  /*
   * 查询出来的图片集合
   */
  List<dynamic> mQueryMedia = [];

  /*
   * 图片上传保存下来的结果
   */
  List<Map<String, dynamic>> mMediaUpload = new List();

  CtrlDocWidgetBasState()
  {}

  void initState()
  {
    super.initState();
    query();
  }

  Widget build(BuildContext context)
  {
    return new DuplicateWidget(
      mMediaList: mediaList,
      mIsEdit: widget.initPara[BasMapKeyConstant.MAP_KEY_ISEDIT],
      mNullable: widget.initPara[BasMapKeyConstant.MAP_KEY_NULLABLE],
      valueChangedMethod: (item)
      {
        doClickDuplicateWidget(item);
      },
      valueDeleteMethod: (map)
      {
        if (map[BasMapKeyConstant.MAP_KEY_PATH].contains(BasSoftwareConstant.NETWORK_HTTP) ||
            map[BasMapKeyConstant.MAP_KEY_PATH].contains(BasSoftwareConstant.NETWORK_HTTPS))
        {
          dynamic item = mQueryMedia[map[BasMapKeyConstant.MAP_KEY_POSITION]];
          SvrDocService.deleteMedia(item[BasMapKeyConstant.MAP_KEY_ID].toString(), this);
        }
        else
        {
          Map<String, dynamic> item;
          for (int i = 0; i < mMediaUpload.length; i ++)
          {
            Map<String, dynamic> index = mMediaUpload[i];
            if (map[BasMapKeyConstant.MAP_KEY_PATH] == index[BasMapKeyConstant.MAP_KEY_PATH])
            {
              item = index;
              break;
            }
          }
          if (!CxTextUtil.isEmptyMap(item))
          {
            mMediaUpload.remove(item);
          }
        }
      },);
  }


  @override
  void onNetWorkFaild(String method, Object values)
  {
    if (method == "queryMedia")
    {}
    else
    {
      super.onNetWorkFaild(method, values);
    }
  }

  /*
   * 网络层接口回调
   */
  @override
  void onNetWorkSucceed(String method, Object values)
  {
    if (method == "queryMedia")
    {
      setState(()
      {
        if (values is List)
        {
          mQueryMedia = values;
          values.forEach((value)
          {
            String url = convertThumbUrl("ids=" + (value[BasMapKeyConstant.MAP_KEY_ID]).toString());
            url = url + BasStringValueConstant.STR_COMMON_COMMA + value['filename'];
            mediaList.add(url);
          });
        }
      });
    }
    else if (method == "createMedia")
    {
      mMediaUpload.add(values);
    }
    else if (method == "deleteMedia")
    {
      showToast(MessageConstant.MSG_DELETE_SUCCESS);
    }
    else
    {
      super.onNetWorkSucceed(method, values);
    }
  }

  /*
   * 查询图片
   */
  void query()
  {
    if (!CxTextUtil.isEmptyObject(widget.initPara) && !CxTextUtil.isEmptyObject(widget.initPara[DBFldConstant.FLD_ID]))
    {
      SvrDocService.queryMedia(
          widget.initPara[DBFldConstant.FLD_MAJOR], widget.initPara[DBFldConstant.FLD_MINOR],
          widget.initPara[DBFldConstant.FLD_ID], this);
    }
  }

  /*
   * 点击图片响应事件
   */
  void doClickDuplicateWidget(item)
  {
    if (item is File)
    {
      Object entityID = "0";
      if (!CxTextUtil.isEmptyObject(widget.initPara))
      {
        entityID = widget.initPara[DBFldConstant.FLD_ID];
      }
      SvrDocService.createMedia(entityID, item, this);
    }
    else
    {

    }
  }

  /*
   * 保存图片
   */
  void saveTempFile(Map<String, Object> map)
  {
    if (CxTextUtil.isEmptyList(mMediaUpload))
    {
      return;
    }
    String filenames = ArrayUtil.mapKeyToString(mMediaUpload, "filename");
    SvrDocService.saveTempFile(filenames, this);
    inserts(map);
  }

  /*
   * 写入media表数据
   */
  void inserts(Map<String, Object> map)
  {
    String title = ArrayUtil.mapKeyToSubString(mMediaUpload, "title");
    String filename = ArrayUtil.mapKeyToString(mMediaUpload, "filename");
    String filelens = ArrayUtil.mapKeyToString(mMediaUpload, "filelength");
    map["titles"] = title.length > 60 ? title.substring(0, 60) : title;
    map["filenames"] = filename;
    map["filelens"] = filelens;
    SvrDocService.inserts(map, this);
  }

  /*
   * http://140.143.94.155:8080/testoa/DocGetSvr?cmd=download&ids=145
   * @param thumbUrl 举例：【thumbUrl= ids=145】
   */
  String convertThumbUrl(String thumbUrl)
  {
    return UrlConstant.BASE_URL + BasStringValueConstant.STR_COMMON_SLASH +
        HttpParamKeyValue.PARAM_KEY_METHOD_DocGetSvr +
        BasStringValueConstant.STR_COMMON_QUESTION + HttpParamKeyValue.PARAM_KEY_CMD +
        BasStringValueConstant.STR_COMMON_EQUEL + HttpParamKeyValue.PARAM_VALUE_Download +
        BasStringValueConstant.STR_COMMON_AN_DE + thumbUrl;
  }

  /*
   * http://27.115.34.203:10067//uploadfile/12/79/0/127944.mp4
   * @param thumbUrl 举例：【thumbUrl= 12/56/0/125684.mp4】
   */
  String convertThumbUrl2(String thumbUrl,{String catalog:'uploadfile'})
  {
    return UrlConstant.BASE_URL + BasStringValueConstant.STR_COMMON_SLASH +
        catalog + BasStringValueConstant.STR_COMMON_SLASH + thumbUrl;
  }

  /*
   * 是包含附件
   * true 有附件
   */
  bool hasDuplicateDoc()
  {
    if (mediaList.length > 0 || mMediaUpload.length > 0)
    {
      return true;
    }
    return false;
  }
}


/*
 * 类描述：模块提供的Service其他模块调用本模块对外提供的相关方法
 * 作者：郑朝军 on 2019/6/6
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2019/6/6
 * 修改备注：
 */
class CtrlDocWidgetBasService extends InterfaceBaseImpl
{
  @override
  Widget runWidget({dynamic initPara})
  {
    return new CtrlDocWidgetBas(initPara: initPara);
  }
}
